package com.njworkorder.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njworkorder.DTO.WorkSpaceAddDto;
import com.njworkorder.Entity.MeSection;
import com.njworkorder.Entity.MonthExamine;
import com.njworkorder.Entity.Section;
import com.njworkorder.Entity.Workspace;
import com.njworkorder.Handler.ScheduledTasks;
import com.njworkorder.Service.MonthExamineService;
import com.njworkorder.Service.WorkspaceService;
import com.njworkorder.Utils.NoCode;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Tag(name = "工区管理", description = "工区管理相关接口")
@RestController
@RequestMapping("/workspace")
public class WorkspaceController {

    @Autowired
    private ScheduledTasks  scheduledTasks;

    private final WorkspaceService workspaceService;
    private final MonthExamineService monthExamineService;
    public WorkspaceController(WorkspaceService workspaceService, MonthExamineService monthExamineService) {
        this.workspaceService = workspaceService;
        this.monthExamineService = monthExamineService;
    }

    @Operation(summary = "添加工区信息")
    @PostMapping("/addInfo")
    public Result<String> addInfo(@RequestBody WorkSpaceAddDto workSpaceAddDto,
                                  @RequestHeader("Create-Ap-Id") String createApId) {
        Workspace works = new Workspace();
        BeanUtils.copyProperties(workSpaceAddDto, works);
        works.setCreateApId(createApId);

        works.setWorkspaceNo(NoCode.JSJK + NoCode.GQ.name() + workspaceService.getUpToDateWorkspaceNo());

        boolean save = workspaceService.save(works);
        if (save) {
            return ResultUtil.success("添加成功");
        }
        return ResultUtil.fail("添加失败");
    }

    @Operation(summary = "修改工区信息")
    @PostMapping("/updateInfoById/{id}")
    public Result<String> updateInfoById(@PathVariable("id") String id,@RequestBody WorkSpaceAddDto workSpaceAddDto) {
        Workspace works = new Workspace();
        BeanUtils.copyProperties(workSpaceAddDto, works);
        works.setId(id);

        boolean update = workspaceService.updateById(works);
        if (update) {
            return ResultUtil.success("修改成功");
        }
        return ResultUtil.fail("修改失败");
    }

    @GetMapping("/getInfoById")
    @Operation(summary = "根据id获取工区信息")
    public Result<Workspace> getInfoById(@RequestParam("id") String id) {
        Workspace section = workspaceService.getById(id);
        return ResultUtil.success(section);
    }

    @Operation(summary = "根据id删除工区信息")
    @GetMapping("/deleteInfoById")
    public Result<String> deleteInfoById(@RequestParam("id") String id) {
        boolean remove = workspaceService.removeById(id);
        if (remove) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.fail("删除失败");
    }

    @GetMapping("/getList")
    @Operation(summary = "获取工区列表")
    public Result<Page<Workspace>> getList(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize) {
        LambdaQueryWrapper<Workspace> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.apply("1=1");
        queryWrapper.orderByDesc(Workspace::getPublishTime);
        Page<Workspace> page = new Page<>(pageIndex, pageSize);
        return ResultUtil.success(workspaceService.page(page, queryWrapper));
    }

    @GetMapping("/getListByCompanyNo")
    @Operation(summary = "根据公司编号获取工区列表")
    public Result<List<Workspace>> getListByWorkspaceId(@RequestParam("companyNo") String companyNo) {
        LambdaQueryWrapper<Workspace> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Workspace::getCompanyNo, companyNo);
        queryWrapper.orderByDesc(Workspace::getPublishTime);
        List<Workspace> list = workspaceService.list(queryWrapper);
        return ResultUtil.success(list);
    }

    @Operation(summary = "获取考核结果统计")
    @GetMapping("/getARS")
    public Result<List<Map<String,Object>>> getARS(@Schema(description = "时间如一月,传1") @RequestParam("time") String time,
                                                   @RequestParam("wkspId") String wkspId) {

        List<String> list2 = Arrays.asList(wkspId.split(","));

//        LambdaQueryWrapper<Workspace> wrapper1 = new LambdaQueryWrapper<Workspace>()
//                //.eq(Workspace::getId, wkspId)
//                .in(Workspace::getId, list2);
//        List<Workspace> list1 = workspaceService.list(wrapper1);

        MPJLambdaWrapper<MonthExamine> wrapper = new MPJLambdaWrapper<MonthExamine>()
                .select(MonthExamine::getId,MonthExamine::getAmount,MonthExamine::getWorkspaceId)
                //.selectAs(Section::getWorkspaceId,MonthExamine::getCreateApId)
                .selectAs("GROUP_CONCAT(t2.section_name SEPARATOR ',')",MonthExamine::getUnitAoId)

                .leftJoin(MeSection.class,MeSection::getMeId,MonthExamine::getId)
                .leftJoin(Section.class,Section::getId,MeSection::getSectionId)

                .eq(MonthExamine::getEndMonth, time)
                .in(!list2.isEmpty(),MonthExamine::getWorkspaceId, list2)
                .groupBy(MonthExamine::getId);
        List<MonthExamine> monthExamines = monthExamineService.selectJoinList(MonthExamine.class, wrapper);

        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("id","工区id");
        map.put("workspaceName","工区名称");


        List<Map<String,Object>> mapm;
        Map<String,Object> mapc;
//        for (Workspace workspace : list1) {
//            map = new HashMap<>();
//            map.put("id",workspace.getId());
//            map.put("workspaceName",workspace.getWorkspaceName());
//            List<MonthExamine> list = monthExamines.stream().filter(f -> f.getWorkspaceId().equals(workspace.getId())).toList();
            mapm = new ArrayList<>();
            for (MonthExamine monthExamine : monthExamines) {
                mapc = new HashMap<>();
                mapc.put("sectionName",monthExamine.getUnitAoId());
                mapc.put("amount",monthExamine.getAmount());
                mapm.add(mapc);
            }
            map.put("list",mapm);
            maps.add(map);
//        }

        return ResultUtil.success(maps);
    }



    @GetMapping("/test")
    public String test() throws ParseException {
        //scheduledTasks.scheduleTaskWithCronExpression2();

        return  "";
    }

}
